package com.software.car.controller;

import com.software.car.api.UserService;
import com.software.car.common.utils.CommonResult;
import com.software.car.entity.dto.request.WeChatLoginRequest;
import com.software.car.entity.dto.response.UserResponse;
import com.software.car.common.utils.JwtUtil;
import com.software.car.entity.dto.request.WebLoginRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @Description
 * @Author 魔法はまだ解けない
 * @Date 2021/1/21
 */
@RestController
@RequestMapping("/public")
public class LoginController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserService userService;

    /**
     * 公共
     * 微信登陆
     * @param weChatLoginDtoa
     * @return 返回token
     */
    @PostMapping("/login/wx")
    public CommonResult wxLogin(@RequestBody WeChatLoginRequest weChatLoginDtoa) {
        UserResponse user = userService.getUser(weChatLoginDtoa);
        HashMap<String, Object> hashMap = loginRes(user);
        return CommonResult.success(hashMap);
    }
    /**
     * 公共
     * Web登陆
     * @param webLoginRequest
     * @return
     */
    @PostMapping("/login/web")
    public CommonResult WebLogin(@RequestBody WebLoginRequest webLoginRequest){
        UserResponse user = userService.getUser(webLoginRequest);
        HashMap<String, Object> hashMap = loginRes(user);
        return CommonResult.success(hashMap);
    }


    /**
     * 方法：
     * 封装用户登陆信息
     * 并打印日志
     * @param user
     * @return
     */
    private HashMap<String, Object> loginRes(UserResponse user){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", JwtUtil.generate(user.getId()));
        hashMap.put("user",user);
        logger.info("用户："+user.getName()+" || id："+user.getId()+" ||登录成功");
        return hashMap;
    }
}
